package cn.com.enboga.musicbox.control
{
	import cn.com.enboga.musicbox.model.ModelLocator;
	import cn.com.enboga.musicbox.utils.EncodeUtils;
	
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.media.Sound;
	import flash.media.SoundMixer;
	import flash.net.URLRequest;
	
	public class MusicControl
	{
		//获得ModelLocator 实例
		internal var musicBox:ModelLocator = ModelLocator.getInstance();
		
		/**继续播放*/
		public function play():void{
			if(musicBox._playing){
				musicBox._position = musicBox._soundChang.position;
				musicBox._soundChang.stop();
			}else{
				musicBox._soundChang = musicBox._sound.play(musicBox._position);
			}
			musicBox._playing = !musicBox._playing;
		}
		
		/**暂停*/
		public function pause():void{
			musicBox._soundChang.stop();
			musicBox._playing = false;
		}
		
		/**停止*/
		public function stop():void{
			SoundMixer.stopAll();
			musicBox._playing = false;
		}
		
		/**从某处开始新的播放*/
		public function newPlay(url:String, position:int):void{
			if(musicBox._soundChang != null){
				musicBox._soundChang.stop();
				//musicBox._sound.close();
			}
			musicBox._sound = new Sound();
			musicBox._sound.load(new URLRequest(url), musicBox._buffer);
			musicBox._sound.addEventListener(Event.ID3, onID3);
			musicBox._soundChang = musicBox._sound.play(position);
			musicBox._soundChang.soundTransform = musicBox._transform;
			musicBox._soundChang.addEventListener(Event.SOUND_COMPLETE, onComplete);
			musicBox._playing = true;
			musicBox._timer.start();
		}
		
		/** 当歌曲播放完毕 */
		public function onComplete(event:Event):void{
			//设置播放位置
			if(musicBox._playIndex < musicBox._musicInfoList.length-1){
				musicBox._playIndex++;
			}else{
				musicBox._playIndex = 0;
			}
			
			playNextSong();
		}
		
		/** 设置歌曲ID3信息 */
		public function onID3(event:Event):void{
			var songName:String = EncodeUtils.toUtf8(musicBox._sound.id3.songName);
			var artist:String = EncodeUtils.toUtf8(musicBox._sound.id3.artist);
				
			musicBox._songName = artist + " - " + songName;
		}
		
		/** 下一曲 */
		public function playNextSong():void{
			var file:File = musicBox._musicInfoList[musicBox._playIndex] as File;
			newPlay(file.url, 0);
		}
	}
}